import React, { Component } from 'react';
// import axios from 'axios';
import PubSub from 'pubsub-js';

export default class List extends Component {
  searchValue = async () => {
    const {
      input1: { value: user }
    } = this;
    // const { getUsers } = this.props;
    // getUsers({ isFirst: false, isLoading: true });

    // 发布消息  传递参数去list组件中
    PubSub.publish('updateState', { isFirst: false, isLoading: true });
    // 使用axios发送网络请求
    /* axios({
      url: '/api/search/users',
      method: 'get',
      params: {
        q
      }
    }).then(
      res => {
        console.log('res', res);

        // getUsers({ isLoading: false });
        const {
          data: { items: users }
        } = res;
        // getUsers({ userList: users });
        PubSub.publish('updateState', { userList: users, isLoading: false });
      },
      err => {
        // getUsers({ err: err.message, isLoading: false });
        PubSub.publish('updateState', { err: err.message, isLoading: false });
      }
    ); */

    // 使用fetch发送网络请求
    // const newUser = {
    //   q: user
    // };

    // fetch优化前的写法
    /*     fetch(`/api/search/users?q=${user}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then(
        res => {
          console.log('联系服务器成功了', res);
          return res.json();
        },
        err => {
          console.log('联系服务器成功了', err);
          return new Promise();
        }
      )
      .then(
        res => {
          console.log('返回数据', res);
        },
        err => {
          console.log('失败', err);
        }
      ); */

    // fetch优化后的写法
    /*     fetch(`/api/search/users?q=${user}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then(res => {
        console.log(res);
        return res.json();
      })
      .then(data => {
        console.log(data);
        const { items: userList } = data;
        PubSub.publish('updateState', { userList, isLoading: false });
      })
      .catch(err => {
        console.log(err);
      }); */

    try {
      const res = await fetch(`/api/search/users?q=${user}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      const data = await res.json();
      const { items: userList } = data;
      PubSub.publish('updateState', { userList, isLoading: false });
    } catch (err) {
      PubSub.publish('updateState', { err: err.message, isLoading: false });
    }
  };
  render() {
    return (
      <section className="jumbotron">
        <h3 className="jumbotron-heading">Search Github Users</h3>
        <div>
          <input ref={c => (this.input1 = c)} type="text" placeholder="enter the name you search" />
          &nbsp;<button onClick={this.searchValue}>Search</button>
        </div>
      </section>
    );
  }
}
